<?php

/* 会员 member */

class MemberModel extends BaseModel {

    var $table = 'member';
    var $prikey = 'user_id';
    var $_name = 'member';

    /* 与其它模型之间的关系 */
    var $_relation = array(
        'has_app_token' => array(
            'model' => 'app_token',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
            'dependent' => true
        ),
        // 一个会员拥有多个积分记录
        'has_integral_log' => array(
            'model' => 'integral_log',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
            'dependent' => true
        ),
        // 一个会员拥有一个店铺，id相同
        'has_store' => array(
            'model' => 'store', //模型的名称
            'type' => HAS_ONE, //关系类型
            'foreign_key' => 'store_id', //外键名
            'dependent' => true           //依赖
        ),
        'has_sdinfo' => array(
            'model' => 'sdinfo',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
            'dependent' => true
        ),
        'manage_mall' => array(
            'model' => 'userpriv',
            'type' => HAS_ONE,
            'foreign_key' => 'user_id',
            'ext_limit' => array('store_id' => 0),
            'dependent' => true
        ),
        // 一个会员拥有多个收货地址
        'has_address' => array(
            'model' => 'address',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
            'dependent' => true
        ),
        // 一个用户有多个订单
        'has_order' => array(
            'model' => 'order',
            'type' => HAS_MANY,
            'foreign_key' => 'buyer_id',
            'dependent' => true
        ),
        // 一个用户有多个心愿单记录
        'user_wish_log' => array(
            'model' => 'wish_log',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
            'dependent' => true
        ),
        // 一个用户有多条收到的短信
        'has_received_message' => array(
            'model' => 'message',
            'type' => HAS_MANY,
            'foreign_key' => 'to_id',
            'dependent' => true
        ),
        // 一个用户有多条发送出去的短信
        'has_sent_message' => array(
            'model' => 'message',
            'type' => HAS_MANY,
            'foreign_key' => 'from_id',
            'dependent' => true
        ),
        // 会员和商品是多对多的关系（会员收藏商品）
        'collect_goods' => array(
            'model' => 'goods',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'collect', //中间表名称
            'foreign_key' => 'user_id',
            'ext_limit' => array('type' => 'goods'),
            'reverse' => 'be_collect', //反向关系名称
        ),
        // 会员和店铺是多对多的关系（会员收藏店铺）
        'collect_store' => array(
            'model' => 'store',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'collect',
            'foreign_key' => 'user_id',
            'ext_limit' => array('type' => 'store'),
            'reverse' => 'be_collect',
        ),
        // 会员和店铺是多对多的关系（会员拥有店铺权限）
        'manage_store' => array(
            'model' => 'store',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'user_priv',
            'foreign_key' => 'user_id',
            'reverse' => 'be_manage',
        ),
        // 会员和好友是多对多的关系（会员拥有多个好友）
        'has_friend' => array(
            'model' => 'member',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'friend',
            'foreign_key' => 'owner_id',
            'reverse' => 'be_friend',
        ),
        // 好友是多对多的关系（会员拥有多个好友）
        'be_friend' => array(
            'model' => 'member',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'friend',
            'foreign_key' => 'friend_id',
            'reverse' => 'has_friend',
        ),
        //用户与商品咨询是一对多的关系，一个会员拥有多个商品咨询
        'user_question' => array(
            'model' => 'goodsqa',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
        ),
        // 会员和团购活动是多对多的关系（会员收藏商品）
        'join_groupbuy' => array(
            'model' => 'groupbuy',
            'type' => HAS_AND_BELONGS_TO_MANY,
            'middle_table' => 'groupbuy_log', //中间表名称
            'foreign_key' => 'user_id',
            'reverse' => 'be_join', //反向关系名称
        ),
        // 一个会员发起一个团购
        'start_groupbuy' => array(
            'model' => 'groupbuy',
            'type' => HAS_ONE,
            'foreign_key' => 'store_id',
            'dependent' => true
        ),
          // 一个用户可以接受多个消息
        'has_chatlog' => array(
            'model' => 'chatlog',
            'type' => HAS_MANY,
            'foreign_key' => 'receiverid',
            'dependent' => true,
        ),
        // 一个用户对应多个账单
        'user_commission_account' => array(
            'model' => 'commission_account',
            'type' => HAS_MANY,
            'foreign_key' => 'user_id',
            'dependent' => true,
        ),
    );
    var $_autov = array(
        'user_name' => array(
            'required' => true,
            'filter' => 'trim',
        ),
        'password' => array(
            'required' => true,
            'filter' => 'trim',
            'min' => 6,
        ),
    );

    /*
     * 判断名称是否唯一
     */

    function unique($user_name, $user_id = 0) {
        $conditions = "user_name = '" . $user_name . "'";
        $user_id && $conditions .= " AND user_id <> '" . $user_id . "'";
        return count($this->find(array('conditions' => $conditions))) == 0;
    }

    function drop($conditions, $fields = 'portrait') {
        if ($droped_rows = parent::drop($conditions, $fields)) {
            restore_error_handler();
            $droped_data = $this->getDroppedData();
            foreach ($droped_data as $row) {
                $row['portrait'] && @unlink(ROOT_PATH . '/' . $row['portrait']);
            }
            reset_error_handler();
        }
        return $droped_rows;
    }

    function get_grade_info($user_id) {
        if (!$user_id) {
            return;
        }
        $user = $this->get($user_id);
        if (!$user) {
            return;
        }
        $ugrade_mod = &m('ugrade');
        $ugrade = $ugrade_mod->get(array('conditions' => 'grade_id =' . $user['ugrade']));
        $higher_grade = $ugrade_mod->get(array(
            'conditions' => 'grade=' . ($ugrade['grade'] + 1),
        ));
        $data = array(
            'distant_growth' => $higher_grade['growth_needed'] - $user['total_integral'],
            'grade_name' => $ugrade['grade_name'],
            'grade_icon' => $ugrade['grade_icon'],
            'total_integral' => $user['total_integral'],
            'higher_grade_name' => $higher_grade['grade_name']
        );
        return $data;
    }


    /* 改变用户可用金额,同时做记录 
     * user_id
     * user_name
     * order_id
     * order_sn
     * type
     * states
     * money
     * money_flow
     * complete
     * log_text
     * add_time
     * 
     * edit_field 表示是处理可用金额  还是 冻结金额
     */

    function change_money($data, $edit_field = 'money') {
        $member = $this->getAll('SELECT * FROM '.$this->table.' WHERE user_id='.$data['user_id'].' FOR UPDATE');
        if (empty($member) || !is_array($member)) {
            $this->_error('用户不存在');
            return FALSE;
        }
        $member=current($member);
        if (!$data['user_name']) {
            $data['user_name'] = $member['user_name'];
        }
        if ($data['money_flow'] == 'income') {
            if ($edit_field == 'money_dj') {
                $new_money = array(
                    'money_dj' => $member['money_dj'] + $data['money'],
                );
            } else {
                $new_money = array(
                    'money' => $member['money'] + $data['money'],
                );
            }
        } elseif ($data['money_flow'] == 'outlay') {
            if ($edit_field == 'money_dj') {
                $new_money = array(
                    'money_dj' => $member['money_dj'] - $data['money'],
                );
                if ($new_money['money_dj'] < 0) {
                    $this->_error('冻结金额小于可用金额');
                    return FALSE;
                }
            } else {
                $new_money = array(
                    'money' => $member['money'] - $data['money'],
                );
                if ($new_money['money'] < 0) {
                    $this->_error('可用金额小于可用金额');
                    return FALSE;
                }
            }
        } else {
            $this->_error('资金输入参数错误');
            return FALSE;
        }
        
        if($new_money['money']>99999999.99){
            $this->_error('资金输入参数错误');
            return FALSE;
        }
        
        $mysql_flag=$this->edit($data['user_id'], $new_money);
        if(!$mysql_flag){
            $this->_error('系统繁忙，请重试');
            return FALSE;
        }else{
            return $this->add_account_log($data);
        }
    }

    function add_account_log($data) {
        $account_log_mod = & m('account_log');
        if (empty($data['add_time'])) {
            $data['add_time'] = gmtime();
        }
        return $account_log_mod->add($data);
    }

    //通过分享注册
    function share_register($user_name, $password='', $email='', $local_data = array()) {
        $usernameResult = $this->check_username($user_name);
        if ($usernameResult['code'] != 1) {
            return $usernameResult;
        }

      /*  $emailResult = $this->check_email($email);
        if ($emailResult['code'] != 1) {
            return $emailResult;
        }
        dump(333);*/

        $mobileResult = $this->check_mobile($local_data['phone_mob']);
        if ($mobileResult['code'] != 1) {
            return $mobileResult;
        }
        $local_data['user_name'] = $user_name;
        $password && $local_data['password'] = md5($password);
        $local_data['email'] = $email;
        $local_data['reg_time'] = time();
        $message = '用于分享注册：拿到参数'.json_encode($local_data);
        $this->writeLog($message);
        $user_id = $this->add($local_data);
        $arr['code'] = -1;
        $arr['msg'] = '注册失败';
        if($user_id){
            $message = '新用户注册成功：用户id：'.$user_id;
            $this->writeLog($message);
            $arr['code'] = 1;
            $arr['result'] = $user_id;
        }else{
            $this->writeLog('分享注册：参数'.json_encode($local_data).' 注册失败');
        }
        return $arr;
    }

    /**
     *    检查电子邮件是否唯一
     *
     *    @author    Garbin
     *    @param     string $email
     *    @return    bool
     */
    function check_email($email) {
        /* 暂时无此设置 */
        if (empty($email)) {
            return true;
        }
        $arr['code'] = 1;
        //验证是否为邮箱
        if (!preg_match("/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i", $email)) {
            $arr['code'] = -1;
            $arr['msg'] = '邮箱格式错误';
        }
        $info = $this->get("email='{$email}' or user_name='{$email}'");
        if (!empty($info)) {
            $arr['code'] = -1;
            $arr['msg'] = '邮箱已存在';
        }
        return $arr;
    }

    /**
     *    检查用户名是否唯一
     *
     *    @author    Garbin
     *    @param     string $user_name
     *    @return    bool
     */
    function check_username($user_name) {
        $info = $this->get("user_name='{$user_name}' or phone_mob='{$user_name}' or email='{$user_name}'");
        $arr['code'] = 1;
        if (!empty($info)) {
            $arr['code'] = -1;
            $arr['msg'] = '用户已存在';
        }
        return $arr;
    }

    /**
     *    检查手机号码是否唯一
     *
     *    @author    Garbin
     *    @param     string $mobile
     *    @return    bool
     */
    function check_mobile($mobile) {
        if (empty($mobile)) {
            return true;
        }
        $arr['code'] = 1;
        //验证是否为手机号
        if (!preg_match("/^1\d{10}$/", $mobile)) {
            $arr['code'] = -1;
            $arr['msg'] = '手机号格式错误';
        }
        $info = $this->get("phone_mob='{$mobile}' or user_name='{$mobile}'");
        if (!empty($info)) {
            $arr['code'] = -1;
            $arr['msg'] = '手机号已存在';
        }
        return $arr;
    }
    
    function writeLog($mes)
    {
        $years = date('Y-m-d');
        //设置路径目录信息
        $url  = '../temp/logs/'.$years.'/'.$years.'_request_log.txt';
        //取出目录路径中目录(不包括后面的文件)
        $dir_name = dirname($url);
        //如果目录不存在就创建
        if(!file_exists($dir_name)) {
            $res = mkdir(iconv("UTF-8","GBK",$dir_name),0777,true);
        }
        file_put_contents($url,date('Y-m-d H:i:s').":".$mes."\n",FILE_APPEND);
    }
}

?>